(function () {
    // uploadimage
    var defs = {}; // id -> {dependencies, definition, instance (possibly undefined)}

// Used when there is no 'main' module.  没有设置主模块 默认处理规则
// The name is probably (hopefully) unique so minification removes for releases.
    var register_3795 = function (id) {
        var module = dem(id);
        var fragments = id.split('.');
        var target = Function('return this;')();
        for (var i = 0; i < fragments.length - 1; ++i) {
            if (target[fragments[i]] === undefined) { target[fragments[i]] = {}; }
            target = target[fragments[i]];
        }
        target[fragments[fragments.length - 1]] = module;
    };

    // 检查模块
    var instantiate = function (id) {
        var actual = defs[id];
        var dependencies = actual.deps;
        var definition = actual.defn;
        var len = dependencies.length;
        var instances = new Array(len);
        for (var i = 0; i < len; ++i) { instances[i] = dem(dependencies[i]); }
        var defResult = definition.apply(null, instances);
        if (defResult === undefined) { throw 'module [' + id + '] returned undefined'; }
        actual.instance = defResult;
    };

    // 定义功能模块
    var def = function (id, dependencies, definition) {
        if (typeof id !== 'string') { throw 'module id must be a string'; } else if (dependencies === undefined) { throw 'no dependencies for ' + id; } else if (definition === undefined) { throw 'no definition function for ' + id; }
        defs[id] = {
            deps: dependencies,
            defn: definition,
            instance: undefined
        };
    };

    var dem = function (id) {
        var actual = defs[id];
        if (actual === undefined) { throw 'module [' + id + '] was undefined'; } else if (actual.instance === undefined) { instantiate(id); }
        return actual.instance;
    };

    var req = function (ids, callback) {
        var len = ids.length;
        var instances = new Array(len);
        for (var i = 0; i < len; ++i) { instances[i] = dem(ids[i]); }
        callback.apply(null, instances);
    };

    var ephox = {};

    ephox.bolt = {
        module: {
            api: {
                define: def,
                require: req,
                demand: dem
            }
        }
    };

    var define = def;
    var require = req;
    var demand = dem;
// this helps with minification when using a lot of global references
    var defineGlobal = function (id, ref) {
        define(id, [], function () { return ref; });
    };
    /* jsc
    ["tinymce.plugins.print.Plugin",
    "tinymce.core.PluginManager",
    "tinymce.plugins.print.api.Commands",
    "tinymce.plugins.print.ui.Buttons",
    "global!tinymce.util.Tools.resolve"]
    jsc */
    defineGlobal('global!tinymce.util.Tools.resolve', tinymce.util.Tools.resolve);

    // 图片变化后的回调函数
    function handle(evt,callback){
        var files = Array.prototype.slice.call(evt.target.files);
        var that = this;
        files.forEach(function (file, i) {
            var orientation;
            if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
            var reader = new FileReader();
            reader.onload = function () {

                upload(this.result, file.type, file.name,callback);

                let result = this.result;
                // getImgData(this.result, orientation, function (data) {
                //
                // });
            };
            reader.readAsDataURL(file);
        });
    }

    // 上传图片
    function upload(basestr, type, name, callback){

        var postData = 'file='+ encodeURIComponent(basestr);

        // 选择完毕触发事件  回调
        // 发送请求
        AjaxTemp('/api/upload64',postData ,function () {
                // 正确返回函数
            console.log("success");
        },function () {
            // 错误返回函数
            console.log("error")
        })
    }

    /**
     *   ajax
     * @param url  请求地址
     * @param data  请求参数 {k:v}  格式
     * @param fn
     * @constructor
     */
    var globleEditor = null;

    function AjaxTemp(url, data, fn,error){

        // datat应为'a=a1&b=b1'这种字符串格式，在jq里如果data为对象会自动将对象转成这种字符串格式
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        // 添加http头，发送信息至服务器时内容编码类型
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200 ) {
                console.log( xhr.responseText);
                if(xhr.responseText){
                    var _resObj = JSON.parse(xhr.responseText);
                    var _imageUrl = '<div><img style="width: 100%" src="'+_resObj.data.fullPath+'" /></div>';
                    // console.log(_imageUrl);
                    globleEditor.execCommand('mceInsertContent', false, _imageUrl);
                }else if (xhr.readyState == 4 && (xhr.status != 200)){
                    window.iview.Message.error('图片上传失败');
                }
                // fn.call(this, xhr.responseText);
            }
        };
        xhr.send(data);
    }

    define(
        'tinymce.core.PluginManager',
        [
            'global!tinymce.util.Tools.resolve'
        ],
        function (resolve) {
            return resolve('tinymce.PluginManager');
        }
    );

    define(
        'tinymce.plugins.uploadimage.api.Commands',
        [
        ],
        function () {
            var register = function (editor) {
                editor.addCommand('uploadImage', function () {
                    // editor
                    // editor.getWin().print();
                    var inputNode = document.getElementById("tinymceUpLoadImageNode");
                    if(!inputNode){
                        inputNode = document.createElement('input');
                        inputNode.setAttribute('type', 'file');
                        inputNode.setAttribute('id', 'tinymceUpLoadImageNode');
                        document.body.appendChild(inputNode);
                    }
                    globleEditor = editor;
                    inputNode.onchange = handle;
                    inputNode.click();

                });
            };
            return {
                register: register
            };
        }
    );

    define(
        'tinymce.plugins.uploadimage.ui.Buttons',
        [ ],
        function () {
            var register = function (editor) {
                editor.addButton('uploadimage', {
                    icon: 'image',
                    title: 'uploadimage',
                    cmd: 'uploadImage'
                });

                editor.addMenuItem('uploadimage', {
                    text: 'Print',
                    cmd: 'uploadImage',
                    icon: 'image'
                });
            };

            return {
                register: register
            };
        }
    );


    define(
        'tinymce.plugins.uploadimage.Plugin',
        [
            'tinymce.core.PluginManager',
            'tinymce.plugins.uploadimage.api.Commands',
            'tinymce.plugins.uploadimage.ui.Buttons'
        ],
        function (PluginManager, Commands, Buttons) {
            PluginManager.add('uploadimage', function (editor) {
                Commands.register(editor);
                Buttons.register(editor);
                editor.addShortcut('Meta+L', '', 'uploadImage');
            });

            return function () { };
        }
    );
    dem('tinymce.plugins.uploadimage.Plugin')();
})();
